﻿using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using BEGDC.CC.BL.Common;
using BEGDC.CC.BL.Common.Query;
using BEGDC.CC.BL.UserManagement;
using BEGDC.CC.BL.Workflow;
using BEGDC.CC.Entity;
using BEGDC.CC.Web.UserControls;
using BEGDC.Utility.Castle;
using BEGDC.Utility.ExceptionManagement;
using NetBpm.Util.Client;
using NetBpm.Workflow.Execution;
using NetBpm.Workflow.Execution.EComp;

namespace BEGDC.CC.Web
{
	/// <summary>
	/// Summary description for UserGroupForm.
	/// </summary>
	public class GroupUsersForm : System.Web.UI.Page
	{
		protected System.Web.UI.WebControls.ListBox SourceBox;
		protected System.Web.UI.WebControls.ImageButton btnRemove;
		protected System.Web.UI.WebControls.ImageButton btnRemoveAll;
		protected System.Web.UI.WebControls.ImageButton btnAdd;
		protected System.Web.UI.WebControls.ImageButton btnAddAll;
		protected System.Web.UI.WebControls.ListBox TargetBox;
		protected System.Web.UI.WebControls.Button btnSave;
		protected System.Web.UI.WebControls.Label lbGroupName;
		protected System.Web.UI.WebControls.Label lbGroupDescription;
		protected System.Web.UI.WebControls.Label lbUsersInGroup;
		protected System.Web.UI.WebControls.Label lbUsersOutGroup;
		private int GroupID
		{
			set
			{
				ViewState["groupID"] = value;
			}
			get
			{
				if(ViewState["groupID"] == null)
					return 0;
				return (int)ViewState["groupID"];
			}
		}
	
		private void Page_Load(object sender, System.EventArgs e)
		{
			// Put user code to initialize the page here
			if(!Page.IsPostBack)
			{
				this.GroupID = Convert.ToInt32(Request.QueryString["id"]);
				InitializeGlobalization();
				
				LoadTargetBox();

				if (((BEGDC.CC.BL.Workflow.CCPrincipal)Page.User).Roles.IndexOf("BusinessAdmin") > -1 && ((BEGDC.CC.BL.Workflow.CCPrincipal)Page.User).Roles.IndexOf("RoleAdmin") == -1)
				{
					this.btnSave.Visible = false;
				}
				//else
				//{
				LoadSourceBox();
				//}
			}
		}

		private void InitializeGlobalization()
		{
			IUser iuser = AppContainer.Instance[ServiceConst.UserService] as IUser;
			Role role = iuser.GetRoleByID(this.GroupID);
            this.lbGroupName.Text = "Group (组名): "; //+  role.RoleName;
            this.lbGroupDescription.Text = "Description (描述): ";// + role.Description;
		}

		private void LoadSourceBox()
		{
			IUser iuser = AppContainer.Instance[ServiceConst.UserService] as IUser;
			IList list = iuser.GetNoUserByRole(this.GroupID);

			if(list != null)
			{
				this.SourceBox.Items.Clear();
				for(int i=0; i<list.Count; i++)
				{
					Employee emp = (Employee)list[i];

					ListItem item = new ListItem(emp.NameEN, emp.Id.ToString());
					this.SourceBox.Items.Add(item);
				}
			}
		}

		private void LoadTargetBox()
		{
			IUser iuser = AppContainer.Instance[ServiceConst.UserService] as IUser;
			IList list = iuser.GetUserByRole(this.GroupID);

			if(list != null)
			{
				this.TargetBox.Items.Clear();
				for(int i=0; i<list.Count; i++)
				{
					BEGDC.CC.Entity.UserRole userRole = (BEGDC.CC.Entity.UserRole)list[i];
					//Shaly: 2/2/2007. Shohw Dept. info of user
					//ListItem item = new ListItem(userRole.Employee.ADName+"["+userRole.Employee.EnglishName+"]", userRole.Employee.Id.ToString());
					ListItem item = new ListItem(userRole.Employee.NameEN, userRole.Employee.Id.ToString());
					this.TargetBox.Items.Add(item);
				}
			}
		}


		#region Web Form Designer generated code
		override protected void OnInit(EventArgs e)
		{
			//
			// CODEGEN: This call is required by the ASP.NET Web Form Designer.
			//
			InitializeComponent();
			base.OnInit(e);
		}
		
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{    
			this.btnRemove.Click += new System.Web.UI.ImageClickEventHandler(this.btnRemove_Click);
			this.btnRemoveAll.Click += new System.Web.UI.ImageClickEventHandler(this.btnRemoveAll_Click);
			this.btnAdd.Click += new System.Web.UI.ImageClickEventHandler(this.btnAdd_Click);
			this.btnAddAll.Click += new System.Web.UI.ImageClickEventHandler(this.btnAddAll_Click);
            this.btnSave.Click += new EventHandler(btnSave_Click);
			this.Load += new System.EventHandler(this.Page_Load);

		}
		#endregion

		private void btnRemove_Click(object sender, System.Web.UI.ImageClickEventArgs e)
		{
			try
			{
				int total = this.TargetBox.Items.Count;
				for(int i=0; i<total;)
				{
					ListItem item = this.TargetBox.Items[i];
					if(item.Selected)
					{
						this.SourceBox.Items.Add(item);
						this.TargetBox.Items.Remove(item);
						this.SourceBox.SelectedIndex = this.SourceBox.Items.Count - 1;
						total--;
					}
					else
						i++;
				}
			}
			catch(GDCException gdcEx)
			{
				WebUtility.Go2ErrorPage(this.Page, gdcEx.ErrorNumber);
			}
			catch
			{
				WebUtility.Go2ErrorPage(this.Page, BEGDC.CC.BL.Common.ErrorCode.Other_Exception);
			}
		}

		private void btnRemoveAll_Click(object sender, System.Web.UI.ImageClickEventArgs e)
		{
			try
			{
				while(this.TargetBox.Items.Count > 0)
				{
					ListItem item = this.TargetBox.Items[0];
					this.SourceBox.Items.Add(item);
					this.TargetBox.Items.Remove(item);
				}
			}
			catch(GDCException gdcEx)
			{
				WebUtility.Go2ErrorPage(this.Page, gdcEx.ErrorNumber);
			}
			catch
			{
				WebUtility.Go2ErrorPage(this.Page, BEGDC.CC.BL.Common.ErrorCode.Other_Exception);
			}
		}

		private void btnAdd_Click(object sender, System.Web.UI.ImageClickEventArgs e)
		{
			try
			{
				int total = this.SourceBox.Items.Count;
				for(int i=0; i<total;)
				{
					ListItem item = this.SourceBox.Items[i];
					if(item.Selected)
					{
						this.TargetBox.Items.Add(item);
						this.SourceBox.Items.Remove(item);
						this.TargetBox.SelectedIndex = this.TargetBox.Items.Count - 1;
						total--;
					}
					else
						i++;
				}
			}
			catch(GDCException gdcEx)
			{
				WebUtility.Go2ErrorPage(this.Page, gdcEx.ErrorNumber);
			}
			catch
			{
				WebUtility.Go2ErrorPage(this.Page, BEGDC.CC.BL.Common.ErrorCode.Other_Exception);
			}
		}

		private void btnAddAll_Click(object sender, System.Web.UI.ImageClickEventArgs e)
		{
			try
			{
				while(this.SourceBox.Items.Count > 0)
				{
					ListItem item = this.SourceBox.Items[0];
					this.TargetBox.Items.Add(item);
					this.SourceBox.Items.Remove(item);
				}
			}
			catch(GDCException gdcEx)
			{
				WebUtility.Go2ErrorPage(this.Page, gdcEx.ErrorNumber);
			}
			catch
			{
				WebUtility.Go2ErrorPage(this.Page, BEGDC.CC.BL.Common.ErrorCode.Other_Exception);
			}
		}

        void btnSave_Click(object sender, EventArgs e)
		{
			string source = string.Empty;
			string target = string.Empty;
			string targetName = string.Empty;
			for(int i=0; i<this.SourceBox.Items.Count; i++)
			{
				source += "'" + this.SourceBox.Items[i].Value+"',";
			}
			for(int i=0; i<this.TargetBox.Items.Count; i++)
			{
				target += "'" + this.TargetBox.Items[i].Value+"',";
				targetName += this.TargetBox.Items[i].Text+", ";
			}
			if(source != string.Empty)
				source = source.Substring(0, source.Length-1);
			if(target != string.Empty)
				target = target.Substring(0, target.Length-1);
			if(targetName != string.Empty)
				targetName = targetName.Substring(0, targetName.Length-2);
			if(targetName.Length > 3900)
				targetName = targetName.Substring(0, 3900);

			IUser iuser = AppContainer.Instance[ServiceConst.UserService] as IUser;
			if(iuser.SaveUserRoleByRole(this.GroupID, source, target))
			{
				//Clear Cache
				BEGDC.CC.BL.Workflow.CCPrincipal.ClearPrincipal();

				Page.RegisterClientScriptBlock("","<script>VBAlert('" + BEGDC.CC.Resource.SystemMessage.CR001 + "');</script>");
				
				// Write Log
				IUtility utility = AppContainer.Instance[ServiceConst.UtilityService] as IUtility;
				CCIdentity id = this.User.Identity as CCIdentity;
				BEGDC.CC.Entity.OperationLog log = new BEGDC.CC.Entity.OperationLog();
				log.Module = "UserManagement";
				log.OperationType = "Assign User";
				Employee emp = new Employee();
				emp.Id = id.UserInfo.Id;
				log.Employee = emp;
				log.Time = System.DateTime.Now;
				log.Description = "[Update Role:" + this.lbGroupName.Text + "]  user list: " + targetName;
				utility.SaveOperationLog(log);
			}
			else
				Page.RegisterClientScriptBlock("","<script>alert('" + BEGDC.CC.Resource.SystemMessage.CR002 + "');</script>");

		}
	}
}
